package com.example.demo.service;

import com.example.demo.tools.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: su
 * Date: 2023-04-19
 * Time: 13:23
 */
@Service
public class MailService {
    @Value("${spring.mail.username}")
    private String mailUsername;
    @Value("${spring.mail.ip}")
    private String ip;

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMail(String data, String email) {
        // 邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            // 邮件主题
            message.setSubject("百草邮件");
            // 邮件发送方
            message.setFrom(mailUsername);
            // 邮件接受方
            message.setTo(email);
            // 发送日期
            message.setSentDate(new Date());
            // 邮件正文
            String text = Constant.EMAIL_FIRST + data + Constant.EMAIL_SECOND + ip + "/subscribe/delete?email=" + email + Constant.EMAIL_Third;
            message.setText(text, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        // 发送
        javaMailSender.send(mimeMessage);
    }
}
